<template>
  <!-- 人员能力表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '850px' : '850px'"
    draggable
    @close="closeDialog"
    :destroy-on-close="true"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="技能熟练度" prop="skillProficiency">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.skillProficiency"
              placeholder="请选择技能熟练度"
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('SkillLevel')"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备种类" prop="assetTypeId" style="width: 100%">
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请选择设备种类"
              v-model="formData.assetTypeId"
              :data="catalogList"
              node-key="id"
              :props="{
                label: 'assetTypeName',
                value: 'id',
                children: 'nodes',
              }"
              :render-after-expand="false"
              :check-strictly="true"
              clearable
              style="width: 300px"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="班组" prop="teamId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.teamId"
              placeholder="请输入班组"
              clearable
              style="width: 300px"
              @change="changeCrew"
              filterable
            >
              <el-option
                v-for="item in crewList"
                :key="item.id"
                :label="`${item.teamCode}-${item.teamName}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成员姓名" prop="memberId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.memberId"
              placeholder="请输入成员"
              clearable
              style="width: 300px"
              :disabled="formData.teamId === ''"
              @change="changeMember"
              filterable
            >
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="`${item.memberEmpNo}-${item.memberName}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="是否启用" prop="enabled">
        <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.remarks"
          placeholder="请输入备注"
          clearable
          type="textarea"
        />
      </el-form-item>
      <el-row>
        <el-col :span="24">
          <el-form-item label="附件" labelWidth="82" prop="executeFiles">
            <CommonUploadFile
              :isRead="props.isReadonly"
              :files="formData.files"
              @update-files="updateFormFiles"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="创建时间"
            prop="createTime"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createTime"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="创建人"
            prop="createdUserName"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createdUserName"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="更新时间"
            prop="lastUpdateTime"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdateTime"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="更新人"
            prop="lastUpdatedUserName"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdatedUserName"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      title=""
      :column="2"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">技能熟练度</div>
        </template>
        {{
          dictionaryStore.filterDictName(
            "SkillLevel",
            formData.skillProficiency
          )
        }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备种类</div>
        </template>
        {{ formData.assetTypeName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">班组</div>
        </template>
        {{ formData.teamName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">成员姓名</div>
        </template>

        {{ formData.memberEmpNo }}{{ formData.memberName ? "-" : ""
        }}{{ formData.memberName }}
      </el-descriptions-item>

      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">是否启用</div>
        </template>
        <el-tag v-if="formData.enabled === 1" type="">启用</el-tag>
        <el-tag v-else type="info">停用</el-tag>
      </el-descriptions-item>

      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.remarks || "暂无备注" }}
        </div>
      </el-descriptions-item>

      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">附件</div>
        </template>
        <div v-if="formData.files && formData.files.length">
          <CommonUploadFile
            :showText="false"
            :isRead="props.isReadonly"
            :files="formData.files"
            @update-files="updateFormFiles"
          />
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "COMMONMEMBERABILITYADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);
watch(
  () => props.assetKind,
  (newVal: number) => {},
  {
    immediate: true,
  }
);
const rules = reactive({
  teamId: [{ required: true, message: "请选择班组", trigger: "change" }],
  memberId: [{ required: true, message: "请选择人员", trigger: "change" }],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  assetTypeId: [
    { required: true, message: "请选择设备种类", trigger: "change" },
  ],
  processId: [{ required: true, message: "请选择工序", trigger: "change" }],
  skillProficiency: [
    { required: true, message: "请选择技能熟练程度", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
});
const formRef = ref(ElForm);

let formData = reactive({
  assetKind: props.assetKind,
  id: "",
  memberId: "",
  memberEmpNo: "",
  memberName: "",
  memberCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  workCenterId: "",
  workCenterCode: "",
  processId: "",
  processCode: "",
  processName: "",
  teamId: "",
  teamCode: "",
  teamName: "",
  skillProficiency: "",
  version: "",
  remarks: "",
  files: [],
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  assetTypeId: "",
  assetTypeName: "",
  assetTypeCode: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";

    if (newVal?.id) {
      const {
        id,
        assetKind,
        memberId,
        memberEmpNo,
        memberName,
        memberCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        processId,
        processCode,
        processName,
        teamId,
        teamCode,
        teamName,
        skillProficiency,
        version,
        remarks,
        files,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetTypeId,
        assetTypeName,
        assetTypeCode,
      } = newVal;
      Object.assign(formData, {
        id,
        assetKind,
        memberId,
        memberEmpNo,
        memberName,
        memberCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        processId,
        processCode,
        processName,
        teamId,
        teamCode,
        teamName,
        skillProficiency,
        version,
        remarks,
        files,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetTypeId,
        assetTypeName,
        assetTypeCode,
      });

      getCrews();
      getMember();
    } else {
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.assetKind = props.assetKind;
  formData.memberId = "";
  formData.memberEmpNo = "";
  formData.memberName = "";
  formData.memberCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  formData.teamId = "";
  formData.teamCode = "";
  formData.teamName = "";
  formData.skillProficiency = "";
  formData.version = "";
  formData.remarks = "";
  formData.files = [];
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.assetTypeCode = "";
}

const loading = ref(false);

/** 人员能力保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eamMemberAbility/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
//赋值班组信息及调用人员
const crewList = ref([]);
const changeCrew = (id: any) => {
  formData.teamId = id;
  crewList.value.forEach((item) => {
    if (item.id === id) {
      formData.teamCode = item.teamCode;
      formData.teamName = item.teamName;
    }
  });
  formData.memberId = "";
  formData.memberEmpNo = "";
  formData.memberName = "";
  getMember();
};
//获取班组列表
async function getCrews() {
  await request({
    url: "eam/eamTeam/getAvailableList",
    method: "post",
    data: {},
  }).then((res) => {
    crewList.value = res.data;
  });
}
//人员
const memberList = ref([]);
const changeMember = (id: any) => {
  formData.memberId = id;
  memberList.value.forEach((item) => {
    if (item.id === id) {
      formData.memberEmpNo = item.memberEmpNo;
      formData.memberName = item.memberName;
    }
  });
};
// 根据班组id获取人员列表
async function getMember() {
  await request({
    url: "eam/eamTeam/getDetails",
    method: "post",
    data: {
      id: formData.teamId,
    },
  }).then((res) => {
    memberList.value = res.data;
  });
}

// 设备种类// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/eamCommon/getAvailableTree",
    method: "POST",
    data: { assetKind: formData.assetKind },
  }).then((res) => {
    console.log(res.data);

    catalogList.value = res.data;
  });
};
// 图片处理
function updateFormFiles(val: []) {
  formData.files = val;
}
onMounted(() => {
  getCrews();
  getCAtalogList();
});
</script>
<style lang="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 110px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
